
const {setToken,checkToken}=require('../middleware/Interceptor')
const { APIError, prefix,Pagiation,getTotalPage }=require("../until/until");
const model = require('../model');// 数据源  
const { Op } = require("sequelize");
let User = model.user;   
 //User.sync({ force: true }) //自动创建表
 //await User.drop();//删除与模型相关的表：  
 class UserModel { 
   static async verdictUser(data){ 
	   let res=await User.findOne({where:{name:data.name,password:data.password}}); 
	   if(res){ 
		   let token=setToken(res.dataValues); 
		   return Object.assign({},res.dataValues,{token});
	   }else {
		   return new APIError(401,'没有此用户');
	   } 
   }
   static async getUserById(id){
	   let sqlParam={    where:{id}  }
	   let res= await User.findOne(sqlParam);  
	   return res;
   }
   static async getUserByParam(param) {  
	    console.log("参数",param);    
	   let sqlParam={
	   		   'offset': Number(param.size*(param.current-1)),    // 从第几个开始查询  Number(pageSize*pageNow) 
	   		   'limit':param.size, //每次查询多少个 size  
			    attributes:{exclude:['password']},//exclude不包含
	   		    where:{}
	   }
	   if(param.name)
	   sqlParam.where={name:{ [Op.like]:param.name }};
	   let amount = await User.count(sqlParam);
	   let res= await User.findAll(sqlParam);  
	   let data=Object.assign({},{list:res},{totalPage:getTotalPage(amount,param.size),total:amount,current:param.current,size:param.size})
	  
	   // console.log("获取用户信息",res); 
	return data;
    }
   
  static async createUser(data) { 
        return await User.create({
			name:data.name,
			password: data.password,
			gender: data.gender,
			birth:data.birth, 
			version:1, 
		});
    } 
  
   static updateUser(data){
	   console.log(data);
	   
	   return User.update(data,{where:{id:data.id}})
   }
   static deleteUser(id){ 
         return User.destroy({where:{id}})
   } 
   
   static async findAllByParam(){
   	   let param={ 
   		  'offset': 1,   // 从第几个开始查询  Number(pageSize*pageNow)
   		  'limit': 10,   //每次查询多少个 size
   		  attributes:{exclude:['password']},//exclude不包含
   		  where: { sex:1 } 
   	   }
   	   return await User.findAll(param);
   }  
};
module.exports=UserModel